<template>
  <div class="role-manage">
    <div class="header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        新增角色
      </el-button>
    </div>

    <el-table :data="roles" style="width: 100%" stripe :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="code" label="角色编码" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="permissions" label="权限">
        <template #default="scope">
          <el-tag
            v-for="permission in scope.row.permissions"
            :key="permission"
            style="margin-right: 5px; margin-bottom: 5px;"
            size="small"
          >
            {{ getPermissionName(permission) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="roles.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showAddDialog"
      width="600px"
    >
      <el-form :model="roleForm" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="roleForm.code" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="roleForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="权限配置">
          <el-tree
            ref="permissionTree"
            :data="permissionTreeData"
            :props="treeProps"
            show-checkbox
            node-key="code"
            :default-checked-keys="roleForm.permissions"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRole">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const showAddDialog = ref(false)
const editingRole = ref(null)
const permissionTree = ref()
const currentPage = ref(1)
const pageSize = ref(20)

const roleForm = ref({
  name: '',
  code: '',
  description: '',
  permissions: []
})

const roles = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'admin',
    description: '拥有所有权限',
    permissions: ['user:create', 'user:read', 'user:update', 'user:delete', 'role:create', 'role:read', 'role:update', 'role:delete'],
    createTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '编辑者',
    code: 'editor',
    description: '可以编辑内容',
    permissions: ['user:read', 'user:update', 'role:read'],
    createTime: '2024-01-02 14:30:00'
  },
  {
    id: 3,
    name: '查看者',
    code: 'viewer',
    description: '只能查看内容',
    permissions: ['user:read', 'role:read'],
    createTime: '2024-01-03 09:15:00'
  }
])

const permissionTreeData = ref([
  {
    label: '用户管理',
    code: 'user',
    children: [
      { label: '创建用户', code: 'user:create' },
      { label: '查看用户', code: 'user:read' },
      { label: '更新用户', code: 'user:update' },
      { label: '删除用户', code: 'user:delete' }
    ]
  },
  {
    label: '角色管理',
    code: 'role',
    children: [
      { label: '创建角色', code: 'role:create' },
      { label: '查看角色', code: 'role:read' },
      { label: '更新角色', code: 'role:update' },
      { label: '删除角色', code: 'role:delete' }
    ]
  },
  {
    label: '系统设置',
    code: 'system',
    children: [
      { label: '系统配置', code: 'system:config' },
      { label: '日志管理', code: 'system:log' }
    ]
  }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

const dialogTitle = computed(() => {
  return editingRole.value ? '编辑角色' : '新增角色'
})

const permissionMap = {
  'user:create': '创建用户',
  'user:read': '查看用户',
  'user:update': '更新用户',
  'user:delete': '删除用户',
  'role:create': '创建角色',
  'role:read': '查看角色',
  'role:update': '更新角色',
  'role:delete': '删除角色',
  'system:config': '系统配置',
  'system:log': '日志管理'
}

const getPermissionName = (code) => {
  return permissionMap[code] || code
}

const editRole = (role) => {
  editingRole.value = role
  roleForm.value = { ...role }
  showAddDialog.value = true
}

const deleteRole = (role) => {
  ElMessageBox.confirm('确定要删除此角色吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = roles.value.findIndex(r => r.id === role.id)
    if (index > -1) {
      roles.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const saveRole = () => {
  // 获取选中的权限
  const checkedKeys = permissionTree.value.getCheckedKeys()
  roleForm.value.permissions = checkedKeys

  if (editingRole.value) {
    // 编辑角色
    const index = roles.value.findIndex(r => r.id === editingRole.value.id)
    if (index > -1) {
      roles.value[index] = { ...roleForm.value }
    }
    ElMessage.success('角色更新成功')
  } else {
    // 新增角色
    const newRole = {
      ...roleForm.value,
      id: Date.now(),
      createTime: new Date().toLocaleString()
    }
    roles.value.push(newRole)
    ElMessage.success('角色创建成功')
  }
  
  showAddDialog.value = false
  editingRole.value = null
  roleForm.value = {
    name: '',
    code: '',
    description: '',
    permissions: []
  }
}
</script>

<style scoped>
.role-manage {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
